<template>
	<view>
		<view class='t-toptips' :style="{top: top,background: cubgColor}" :class="[show?'t-top-show':'']">
			<view v-if="loading" class="flex flex-sub">
				<view class="cu-progress flex-sub round striped active sm">
					<view :style="{ background: color,width: value + '%'}"></view>
				</view>
				<text class="margin-left">{{value}}%</text>
			</view>
			<block v-else>{{msg}}</block>
		</view>
		<!-- h5选取文件 -->
		<uni-popup ref="popup" type="bottom" :class="APPTheme" >
			<view class="h5center theme-bg" v-html="html" @input="getFile($event)"></view>
		</uni-popup>
		<web-view ref="webView" v-if="showWebView" :src="webviewUrl" @message="messageFn"></web-view>
		<!-- #ifdef APP-PLUS -->
		<image class="qssImage" v-if="qss.animate_jiami" src="/static/image/qss/jiami.gif"></image>
		<!-- #endif -->
	</view>
	
</template>

<script>
	let that
import {
	mapGetters,
	mapActions
} from 'vuex'
export default {
	computed:{
		...mapGetters(['APPTheme', 'userInfo', 'api'])
	},
	props: {
		top: {
			type: String,
			default: 'auto'
		},
		bgColor: {
			type: String,
			default: 'rgba(49, 126, 243, 0.5)',
		},
		color: {
			type: String,
			default: '#e54d42',
		}
	},
	data() {
		return {
			html:`
			<div style="position: relative;"><button type="default" style="background-color: #007AFF;border: 0;border-radius: 5px;color:#fff;padding:5px 10px">打开文件管理</button>
			<input style="position: absolute;left: 0;top: 0;opacity: 0;" type="file" id="h5File" class="input"/></div>
			`,
			cubgColor: '',
			loading: false,
			value: 5,
			show: false,
			msg: '执行完毕~',
			h5:{
				data:{}
			},
			//自己定义的参数
			query:{},//传递的参数
			showWebView:false,
			webviewUrl:'',
			qss:{
				animate_jiami:false
			}
		}
	},
	mounted() {
		that=this
	},
	methods: {
		//h5选取文件
		getFile(e){
			//console.log(document.getElementById('h5File'));
			document.getElementById('h5File').onchange=function(res){
				that.$refs.popup.close()
				//h5上传
				that.updateH5(res.target.files[0],res.target.files[0].name)
			}
		},
		//h5上传
		updateH5(file,fileName){
			//console.log(file);
			//console.log(that.h5.data.header.Authorization);
			var uploadTask = uni.uploadFile({
				url: that.h5.data.url, //仅为示例，非真实的接口地址
				file: file,
				name: 'file',
				header:{
					'Authorization': that.h5.data.header.Authorization
				},
				success: (res) => {
					if (res.statusCode==200) {
						let data = JSON.parse(res.data);
						//console.log(data);
						if(data.code=='400'){
							uni.reLaunch({
							    url: '/pages/template/login/login'
							});
							return
						}
						if(data.flag){
							that.onCommit(that.$emit('up-success',{fileName,data:{id:data}}))
						}else{
							return that.errorHandler(data.msg,that.upErr);
						}
						
					}else{
						return that.errorHandler('文件上传失败',this.upErr);
					}
				},
				fail: () => this.errorHandler('文件上传失败',this.upErr)
			});
			//监听上传进度
			uploadTask.onProgressUpdate((res)=>{
				that.setdefUI();
				that.value=res.progress
			})
		},
		toast(title = '',{ duration = 2000, icon = 'none'} = {}) {
			uni.showToast({title,duration,icon});
		},
		getRequest(url) {  
			let theRequest = new Object(); 
			let index = url.indexOf("?");
			if (index != -1) {  
				let str = url.substring(index+1);  
				let strs = str.split("&");  
				for(let i = 0; i < strs.length; i ++) {
					theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
				} 
			}  
			return theRequest;  
		},
		
		/*
			app上传文件打开webview
		*/
		appChooseFile() {
			that.showWebView=true
			that.webviewUrl='/hybrid/html/pages/QssUploader.html'
			//设置背景透明
			var pages = getCurrentPages();
			var page = pages[pages.length - 1];
			// #ifdef APP-PLUS
			var currentWebview = page.$getAppWebview();
			setTimeout(function() {
				let wv = currentWebview.children()[0]
				wv.setStyle({background:'transparent'})
			}, 200); //如果是页面初始化调用时，需要延时一下
			//#endif
		},
		//接收到webview传递的参数
		messageFn(event){
			let type=event.detail.data[0].type
			
			if(type=='close'){//关闭当前webview
				that.showWebView=false
			}else if (type=='FileReader'){
				uni.showLoading({
					title: event.detail.data[0].data,
					mask: false
				});
			}else if (type=='upload'){
				that.showWebView=false
				//开启量子加密动画
				that.qss.animate_jiami=true
				//从文件管理系统选取的文件获取到的base64信息
				let data =event.detail.data[0]
				let file={
					base64:data.data,
					fileSize:data.fileSize,
					fileName:data.fileName,
					fileType:data.fileType,
				}
				//console.log(file.fileType);
				/*
				把文件的base64进行量子加密，得到加密后的字符串
				再把字符串传给后台，后台返回文件路径
				*/
			   /* 国科量子加密【字符串】*/
				that.SM4EncryptBigData(file)
				//关闭读取文件动画
				uni.hideLoading()
			}
			
		},
		// 国科量子加密
		async SM4EncryptBigData(file){
			// 需要传入加密的字符串
			let result=await that.$lizhao.QSS.SM4EncryptBigData(file.base64)
			// //console.log('加密结果',result);
			if(result!='会话失效了'){
				//console.log('加密结果的前100个',result.data.slice(0,100));
				file.QSSBase64=result.data//加密密文
				file.secretKey=result.key//加密秘钥
				//0为文件柜，量子文件上传，1为邮箱，量子文件上传
				if(that.query.uploadType==0){
					//文件柜，传入后台字符串生成文件
					that.filingCabinets_upLode(file)
				}else if(that.query.uploadType==1){
					//邮件，传入后台字符串生成文件
					that.Email_upLode(file)
				}
			}
		},
		//传入后台字符串生成文件
		Email_upLode(file){
			var index1=file.fileName.lastIndexOf(".") + 1;
			var suffix=file.fileName.substring(index1,file.fileName.length);
			let req={
				secret:file.QSSBase64,//量子加密后的字符串
				secretKey:file.secretKey,//加密秘钥
				type:that.query.type,//其他参数邮箱附件上传type=0  1头像 2聊天文件
				fileName:file.fileName,//文件名
				suffix:suffix,//文件后缀
				fileSize:file.fileSize,//文件大小
				qss:that.query.qss,//当前上传的是gk加密的
			}
			//console.log('secret',req.secret.slice(0,55));
			that.GLOBAL.doPost(that.api.GLOBAL_rest_vmail_encryption_keepSecret,req).then(res=>{
				//console.log(res);
				that.qss.animate_jiami=false
				if(res.code=='0'){
					uni.showToast({
						title: res.msg,
						icon:'none',
					});
					//关闭当前webview
					that.showWebView=false
					that.$emit('up-success',res.data)
				}
			})
		},
		//传入后台字符串生成文件
		filingCabinets_upLode(file){
			var index1=file.fileName.lastIndexOf(".")+1;
			var suffix=file.fileName.substring(index1,file.fileName.length);
			let req={
				secret:file.QSSBase64,//量子加密后的字符串
				secretKey:file.secretKey,//加密秘钥
				fileType:3,//0文件夹,1word,2excl,3其他
				filingName:file.fileName,//文件名
				parentId:that.query.parentId,//所属文件夹id
				suffix:suffix,//文件后缀
				fileSize:file.fileSize,//文件大小
				filingType:2,//文件柜类型【2加密盘】
			}
			//console.log('parentId',req.parentId,'secret',req.secret.slice(0,55));
			that.GLOBAL.doPost(that.api.GLOBAL_rest_biz_filingCabinets_upLode,req).then(res=>{
				//console.log(res);
				that.qss.animate_jiami=false
				if(res.code=='0'){
					uni.showToast({
						title: res.data.msg,
						icon:'none',
					});
					//关闭当前webview
					that.showWebView=false
					that.$emit('up-success',true)
				}
			})
		},
		//微信上传文件
		wxChooseFile({url,name = 'file',header,...formData} = {}) {},
		//h5上传
		h5FileFn(param){
			that.h5.data=param
			this.$refs.popup.open()
		},
		/* 
		上传
		*/
		upload(param = {}) {
			this.query=param//传过来的参数
			if (this.loading) {
				this.toast('还有个文件玩命处理中，请稍候..');
				return;
			}
			// #ifdef APP-PLUS
				return this.appChooseFile(param);
			// #endif
			
			//#ifdef H5
				return this.h5FileFn(param);
			// #endif
		},
		/* 
		打开文件 
		*/
		open(filePath) {
			let system = uni.getSystemInfoSync().platform;
			if(system == 'ios'){
				filePath = encodeURI(filePath);
			}
			//console.log(filePath);
			uni.openDocument({
				filePath,
				success: (res) => {//console.log('打开文档成功');},
				fail(error) {
					//console.log(error);
				}
			});
			
		},
		/* 
		下载
		 type: temporary=返回临时地址，local=长期保存到本地
		 */
		download(url,type = 'temporary') {
			if (this.loading) {
				this.toast('还有个文件玩命处理中，请稍候..');
				return;
			}
			this.setdefUI();
			
			return new Promise((resolve,reject)=>{
				let downloadTask = uni.downloadFile({
				    url,
				    success: ({statusCode,tempFilePath}) => {
				        if (statusCode === 200) {
							if (type == 'local') {
								uni.saveFile({
									tempFilePath,
									success:({savedFilePath}) => this.onCommit(resolve(savedFilePath)),
									fail: () => this.errorHandler('下载失败',reject)
								});
							}
							else {
								this.onCommit(resolve(tempFilePath))
							}
						}
					},
					fail: () => this.errorHandler('下载失败',reject)
				});
				
				downloadTask.onProgressUpdate(({progress = 0}) => {
					if (progress <= 100) {
						this.$nextTick(()=>{
							this.value = progress;
						});
					}
				});
			})
			
		},
		
		onCommit(resolve) {
			this.msg = '执行完毕~';
			this.loading = false;
			this.cubgColor = 'rgba(57, 181, 74, 0.5)';
			setTimeout(()=>{this.show = false;},1500);
			return resolve;
		},
		
		setdefUI() {
			this.cubgColor = this.bgColor;
			this.value = 0;
			this.loading = true;
			this.show = true;
		},
		
		upErr(errText) {
			this.$emit('up-error',errText);
		},
		
		errorHandler(errText,reject) {
			this.msg = errText;
			this.loading = false;
			this.cubgColor = 'rgba(229, 77, 66, 0.5)';
			setTimeout(()=>{this.show = false;},1500);
			return reject(errText);
		}
	}
}
</script>

<style scoped lang="scss">
	.t-toptips {
		width: 100%;
		padding: 18upx 30upx;
		box-sizing: border-box;
		position: fixed;
		z-index: 90;
		color: #fff;
		font-size: 30upx;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		word-break: break-all;
		opacity: 0;
		transform: translateZ(0) translateY(-100%);
		transition: all 0.3s ease-in-out;
	}
	
	.t-top-show {
		transform: translateZ(0) translateY(0);
		opacity: 1;
	}
	.h5center{
		display: flex;justify-content: center;padding: 10px 0;
		.button{
			background-color: #007AFF;border: 0;border-radius: 5px;
		}
	}
	.qssImage{
		position: fixed;top: 0;bottom: 0;left: 0;right: 0;height: 800rpx;width: 100%;margin: auto;
	}
	
</style>
